<template>
  <div class="app-container">

    <div>
      <el-row :gutter="20" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddPurchase"
            v-hasPermi="['mgcmanage:purchase:add']"
          >添加药品</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddPurchase2"
            v-hasPermi="['mgcmanage:purchase:add']"
          >批量设置</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['mgcmanage:purchase:edit']"
          >暂存</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['mgcmanage:purchase:remove']"
          >提交审核</el-button>
        </el-col>
      </el-row>
    </div>
<br>
<br>
    <el-row :gutter="30">
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

          <el-form-item label="单据id" prop="pid">
            <el-input
              v-model="queryParams.pid"
              placeholder="请输入单据"
              clearable
              size="small"
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="制单人" prop="purchasePeople">
            <el-input
              v-model="queryParams.purchasePeople"
              placeholder="请输入制单人"
              clearable
              size="small"
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="总批发额" prop="pid">
            <el-input
              v-model="queryParams.pid"
              placeholder="请输入总批发额"
              clearable
              size="small"
              style="width: 150px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="供应商列表" prop="sid">
            <el-select
              v-model="queryParams.sid"
              placeholder="请选择供应商"
              clearable
              size="small"
              style="width: 120px"
            >
              <el-option
                v-for="dict in SupplierNames"
                :key="dict.sid"
                :label="dict.supplierName"
                :value="dict.sid"
              />
            </el-select>
          </el-form-item>


          <el-form-item label="制单时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

        </el-form>

        <el-table v-loading="loading" :data="storageList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="100" align="center" />
          <el-table-column label="药品id" align="center" key="storageMedId" prop="storageMedId" v-if="columns[0].visible" />
          <el-table-column label="药品名称" align="center" key="storageMedName" prop="storageMedName"  :show-overflow-tooltip="true"  />
          <el-table-column label="规格" align="center" key="storageSpec" prop="storageSpec"  :show-overflow-tooltip="true" />
          <el-table-column label="生产厂家" align="center"  key="storageMedFactory" prop="storageMedFactory"  :show-overflow-tooltip="true" />
          <el-table-column label="数量" align="center"  key="storageNum" prop="storageNum"  width="120" />
          <el-table-column label="单位" align="center"  key="storageMedCompany" prop="storageMedCompany"  width="120" />
          <el-table-column label="批发价" align="center"  key="storagePrice" prop="storagePrice"  width="120" />
          <el-table-column label="批发额" align="center"  key="" prop=""  width="120" />
          <el-table-column label="批次号" align="center"  key="storageId" prop="storageId"  width="120" />
          <el-table-column label="备注" align="center"  key="remark" prop="remark"  width="120" />
        </el-table>


      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>

      <el-table v-loading="loading" :data="medicineList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="100" align="center" />
        <el-table-column label="药品id" align="center" key="mid" prop="mid" v-if="columns[0].visible" />
        <el-table-column label="药品名称" align="center" key="medicineName" prop="medicineName"  :show-overflow-tooltip="true"  />
        <el-table-column label="药品编码" align="center" key="medicineId" prop="medicineId"  :show-overflow-tooltip="true" />
        <el-table-column label="生产厂家" align="center"  key="lists[0].factoryName" prop="lists[0].factoryName"  :show-overflow-tooltip="true" />
        <el-table-column label="药品类型" align="center" :formatter="medicineTypeFormat" key="medicineType" prop="medicineType"  width="120" />
        <el-table-column label="处方类型" align="center" :formatter="medicineOtcTypeFormat" key="medicineOtcType" prop="medicineOtcType"  width="120" />
        <el-table-column label="处方价格" align="center" key="medicinePrice" prop="medicinePrice"  width="120" />
        <el-table-column label="关键字" align="center" key="medicineKeyword" prop="medicineKeyword"  width="120" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmStorage">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="open2" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量" prop="storageNum">
              <el-input v-model="form.storageNum" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批发价格" prop="storagePrice">
              <el-input v-model="form.storagePrice" placeholder="请输入厂家编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号" prop="storageId">
              <el-input v-model="form.storageId" placeholder="请输入厂家编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入厂家编码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listAllSupplier,getSupplier,updateSupplier,delSupplier} from "@/api/mgcmanage/purchase";
import {listStorage,addStorage} from "@/api/mgcmanage/storage";
import {listMedicine} from "@/api/mgcmanage/medicine";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deepClone } from '../../../utils'


export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购入库表格数据
      purchaseList: null,

      storageList:null,

      medicineList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,

      open2:false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      //入库状态数据字典
      purchaseStatusOptions:[],
      //自定义供应商数据字典
      SupplierNames:[],
      /**药品类型字典*/
      medicineTypeOptions:[],
      //处方类型字典
      medicineOtcTypeOptions:[],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        medicineType: undefined,
        medicineOtcType: undefined,
        medId:undefined,
        status: undefined,
        deptId: undefined

      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ]


    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getAllNames();
    this.getTreeselect();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("purchase_status").then(response => {
      this.purchaseStatusOptions = response.data;
    });
    this.getDicts("med_type").then(response => {
      this.medicineTypeOptions = response.data;
    });
    this.getDicts("med_otc_type").then(response => {
      this.medicineOtcTypeOptions = response.data;
    });

  },
  methods: {

    getAllNames(){
      listAllSupplier().then(resp=>{
        this.SupplierNames=resp.data;
      });
    },

    /** 查询新增采购后的药品和批量的数据列表 */
    getList() {
      this.loading = true;
      listStorage(this.queryParams).then(response => {
          this.storageList = response.data;
          //this.total = response.total;
          this.loading = false;
        }
      );
    },
    getListMedicine() {
      this.loading = true;
      listMedicine(this.queryParams).then(response => {
          this.medicineList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        mid:undefined,
        medicineName: undefined,
        medicineId: undefined,
        medicineType: undefined,
        medicineOtcType: undefined,
        medicineCompany: undefined,
        medicinePrice: undefined,
        medicineNum: undefined,
        medicineMaxValue: undefined,
        medicineHuanSuan: undefined,
        medId:undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 添加药品信息的复选框勾选取消事件
    handleSelectionChange2(selection) {
      // 使用其他数组变量保存所有勾选的行数据
      this.a = selection.map(item => item);
    },
    // 编写确定按钮的方法，把a数组中的每个对象，加到storageList数组中。 storageList.push(a[])
    // 如果a数组和storageList数组中的对象类型不一样，创建一个符合storageList数组中对象类型的变量保存
    confirmStorage(){
      var b = deepClone(this.a);
      for(var i = 0; i < a.length; i++) {
        b.storageMedId = a[i].mid;
        b.storageMedName = a[i].medicineName;
        b.storageMedFactory = a[i].lists[0].factoryName;
        b.storageMedCompany = a[i].medicineCompany;
        this.storageList.push(b);
      }
      his.loading = false;
    },
    // 菜单状态字典翻译
    statusFormat(row, column) {
      if (row.menuType == "F") {
        return "";
      }
      return this.selectDictLabel(this.statusOptions, row.status);
    },

    //药品类型字典翻译
    medicineTypeFormat(row, column) {
      return this.selectDictLabel(this.medicineTypeOptions, row.medicineType);
    },
    //处方类型字典翻译
    medicineOtcTypeFormat(row, column) {
      return this.selectDictLabel(this.medicineOtcTypeOptions, row.medicineOtcType);
    },
    //入库状态字典翻译
    purchaseStatusFormat(row, column) {
      return this.selectDictLabel(this.purchaseStatusOptions, row.purchaseStatus);
    },


    /** 新增按钮操作 */
    handleAddPurchase() {
      //this.reset();
      this.open = true;
      this.getListMedicine();
      this.title = "添加药品信息";

    },
    /** 新增批量配置按钮操作 */
    handleAddPurchase2() {
      //this.reset();
      this.open2 = true;
      this.title = "添加批量配置信息";

    },
    handleAddStorage(){
      this.open = true;
      //this.getListMedicine();
      this.title = "批量设置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sid = row.sid || this.ids;
      getSupplier(sid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改供应商";
      });
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sid != undefined) {
            updateSupplier(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStorage(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sids = row.sid || this.ids;
      this.$confirm('是否确认删除用户编号为"' + sids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSupplier(sids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    }
  }
};
</script>
